package net.example.model.contract;

import com.oraycn.omcs.utils.BufferUtils;

import java.nio.charset.StandardCharsets;
import java.util.List;

import io.netty.buffer.ByteBuf;

public class ChangeGroupMembersContract{

    public String GroupID;
    public List<String> AddedMembers;
    public List<String> RemovedMembers;


    public ChangeGroupMembersContract(){}
    public ChangeGroupMembersContract(String groupID,List<String> addedMembers,List<String> removedMembers)
    {
        this.GroupID=groupID;
        this.AddedMembers=addedMembers;
        this.RemovedMembers=removedMembers;
    }

    public byte[] serialize() throws Exception {
        byte[] bGroupID = GroupID.getBytes(StandardCharsets.UTF_8);

        int contractLen = 4 ;
        ByteBuf body = BufferUtils.newBuffer();
        body.writeInt(0);
        contractLen+=4;
        body.writeInt(AddedMembers.size());
        for (String memberID : AddedMembers) {
            byte[] bMemberID = memberID.getBytes(StandardCharsets.UTF_8);
            contractLen += 4 + bMemberID.length;
            body.writeInt(bMemberID.length);
            body.writeBytes(bMemberID);
        }
        body.writeInt(bGroupID.length);
        body.writeBytes(bGroupID);
        contractLen+=4;
        body.writeInt(RemovedMembers.size());
        for (String memberID : RemovedMembers) {
            byte[] bMemberID = memberID.getBytes(StandardCharsets.UTF_8);
            contractLen += 4 + bMemberID.length;
            body.writeInt(bMemberID.length);
            body.writeBytes(bMemberID);
        }
        int totalLen = body.readableBytes() ;
        body.resetWriterIndex();
        body.writeInt(contractLen);
        byte[] result = new byte[totalLen];
        System.arraycopy(body.array(),0,result,0,result.length);
        return result;
    }

}